package com.cya.forumproject.services.impl;

import com.cya.forumproject.common.AppResult;
import com.cya.forumproject.common.ResultCode;
import com.cya.forumproject.dao.UserMapper;
import com.cya.forumproject.exception.ApplicationException;
import com.cya.forumproject.model.User;
import com.cya.forumproject.services.IUserService;
import com.cya.forumproject.utils.MD5Util;
import com.cya.forumproject.utils.StringUtil;
import com.cya.forumproject.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author ：陈奕安（3048279304@qq.com）
 * @date ：Created in 2025/9/20 10:49
 * @description：
 * @modified By：
 * @version:
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Override
    public void createNormalUser(User user) {
//        非空校验
        if (user==null|| StringUtil.isEmpty(user.getUsername())
    ||StringUtil.isEmpty(user.getNickname())
        ||StringUtil.isEmpty(user.getPassword())
        ||StringUtil.isEmpty(user.getSalt())){
      log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User existUser = userMapper.selectByUserName(user.getUsername());
        //判断用户是否存在
        if (existUser!=null){
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
//         新增用户, 设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date=new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        //写入数据库
        int row = userMapper.insertSelective(user);
        if (row!=1){
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        log.info("新增用户成功,username= "+user.getUsername());
    }

    @Override
    public User selectByUserName(String username) {
        if (StringUtil.isEmpty(username)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
//        返回查询结果
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {

        //1.非空校验
        if (StringUtil.isEmpty(username)||StringUtil.isEmpty(password)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //2.按用户名查询用户信息
        User user=selectByUserName(username);
        //3.对查询结果进行非空校验
        if (user==null){
//            打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString()+",username: "+username);
//            抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));

        }
        //4. 对密码惊醒校验
        String encryptPassword = MD5Util.md5Salt(password, user.getSalt());
        if (!encryptPassword.equalsIgnoreCase(user.getPassword())){
//            打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString()+", 密码错误，username: "+username);
//            抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));

        }
//        登录成功
        log.info("登录成功,username= "+username);
        return user;
    }

    @Override
    public User selectById(Long id) {
        //1.非空校验
        if (id==null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        User user = userMapper.selectByPrimaryKey(id);

        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id==null||id<=0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        //查询用户信息
        User user=userMapper.selectByPrimaryKey(id);
        if (user==null){
            //打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString()+",user id="+id);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));

        }
        User user1=new User();
        user1.setId(user.getId());
        user1.setArticleCount(user.getArticleCount()+1);
        int i = userMapper.updateByPrimaryKeySelective(user1);
        user1.setUpdateTime(new Date());
        if (i!=1){
            log.warn(ResultCode.FAILED.toString()+", 受影响行数不等于1.");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountId(Long id) {
        if (id==null||id<=0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        //查询用户信息
        User user=userMapper.selectByPrimaryKey(id);
        if (user==null){
            //打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString()+",user id="+id);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));

        }
        User user1=new User();
        user1.setId(user.getId());
        user1.setArticleCount(user.getArticleCount()-1);
        if (user1.getArticleCount()<0){
            user1.setArticleCount(0);
        }
        user1.setUpdateTime(new Date());
        int i = userMapper.updateByPrimaryKeySelective(user1);
        if (i!=1){
            log.warn(ResultCode.FAILED.toString()+", 受影响行数不等于1.");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        if (user==null||user.getId()==null||user.getId()<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
//        校验用是否存在
        User existUser = userMapper.selectByPrimaryKey(user.getId());
        if (existUser==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

//        定义一个标志位
        boolean checkAttr=false;
//        对每一个参数进行校验并赋值
        User updateUser=new User();
        updateUser.setId(user.getId());
        if (!StringUtil.isEmpty(user.getUsername())
        &&!user.getUsername().equals(existUser.getUsername())){
//            需要更新用户名进行唯一性校验
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if (checkUser!=null){
                //用户名已经存在
                log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            checkAttr=true;
        }
//        校验昵称
        if (!StringUtil.isEmpty(user.getNickname())
        &&!user.getNickname().equals(existUser.getNickname())){
//            设置昵称
            updateUser.setNickname(user.getNickname());
            checkAttr=true;
        }
//        设置性别
        if (user.getGender()!=null&& user.getGender()!=existUser.getGender()){

            updateUser.setGender(user.getGender());
            if (updateUser.getGender()>2||updateUser.getGender()<0){
                updateUser.setGender((byte) 2);
            }
            checkAttr=true;
        }
//        校验邮箱
        if (!StringUtil.isEmpty(user.getEmail())&&!user.getEmail().equals(existUser.getEmail())){

            updateUser.setEmail(user.getEmail());
            checkAttr=true;
        }
//        校验电话号码
        if (!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existUser.getPhoneNum())){
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr=true;
        }
//        校验个人简介
        if (!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(existUser.getRemark())){
            updateUser.setRemark(user.getRemark());
            checkAttr=true;
        }
//        如过全为false，则不更新
        if (checkAttr==false){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row!=1){
            log.warn(ResultCode.FAILED.toString()+", 受影响行数不等于1.");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
//        非空校验
        if (id == null || id <= 0 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
//        获取用户信息
        User user = userMapper.selectByPrimaryKey(id);
//        用户不存在
        if (user==null||user.getDeleteState()==1){
            //不存在
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //检验老密码是否正确
        //对老密码进行加密
        String oldEncrptyPassword = MD5Util.md5Salt(oldPassword, user.getSalt());

        if (!oldEncrptyPassword.equalsIgnoreCase(user.getPassword())){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        //生成新盐值
        String salt= UUIDUtil.UUID_32();
//         进行加密
        String encryptPassword=MD5Util.md5Salt(newPassword,salt);
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(encryptPassword);
        updateUser.setUpdateTime(new Date());//更新时间

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row!=1){
            log.warn(ResultCode.FAILED.toString()+", 受影响行数不等于1.");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }


    }

}